import qs from 'qs'
import * as auth from 'auth-provider'
import {useAuth} from "../context/auth-context";
import { useCallback } from 'react';

const API = process.env.REACT_APP_API_URL

interface Config extends RequestInit {
    token?: string,
    data?: object
}

export const http = async (endpoint: string, {data, token, headers, ...customConfig}: Config = {}) => {
    const config = {
        method: "GET",
        headers: {
            'Authorization': token ? `Bearer ${token}` : '',
            'Content-Type': data ? 'application/json' : ''
        },
        ...customConfig
    }
    //TO Do toLowerCase
    if (config.method.toUpperCase() === 'GET') {
        endpoint += `?${qs.stringify(data)}`
    } else {
        config.body = JSON.stringify(data || {})
    }
    console.log(`${API}/${endpoint}`, config)
    return window.fetch(`${API}/${endpoint}`, config).then(async response => {
        if (response.status === 401) {
            await auth.logout()
            window.location.reload()
            return Promise.reject({message: "请重新登录"})
        }
        const data = await response.json()
        if (response.ok) {
            return data
        } else {
            return Promise.reject(data)
        }
    })

}

export const useHttp = () => {
    const {user} = useAuth()
    return useCallback( (...[endpoint, config]: Parameters<typeof http>) => http(endpoint, {...config, token: user?.token}),[user?.token])

}

// //联合类型
// let myFavoriteNumber: string | number
// myFavoriteNumber = 'event'
// myFavoriteNumber = 7
// //类型别名
// type FavoriteNumber = string | number
// let roseFavoriteNumber: FavoriteNumber = '8'
// //类型别名在很多情况下可以和interface 互换
// // 主要区别 type FavoriteNumber = string | number 中 interface无法实现 以及交叉类型 type FavoriteNumber = string | number 同样无法实现
//
// // interface Person {
// //     name: string
// // }
// type Person = { name: string }
// const xiaoming: Person = {name: 'xiaoming'}
type Person = {
    name: string,
    age: number
}
// Utility Types： 可以理解为基于ts封装的工具类型;
// // const xiaopang: Person = {name: "123"}
// //Partial 通过遍历后 将所有key变成可选类型
const xiaoming: Partial<Person> = {}
// const xiaohong: Omit<Person, 'name'> = {age: 8}
// const xiaoli: Omit<Person, 'name' | 'age'> = {}
// type PersonKeys = keyof Person
// //Pick 在对象理挑选出来然后组成新的类型
// type PersonOnlyName = Pick<Person, 'name'>
// //Exclude是将这个联合类型中的name过滤掉，其中Personkeys是总的联合类型，
// type Age = Exclude<PersonKeys, 'name'>
// //Partial的实现
// type Partial<T> = {
//     [P in keyof T]?: T[P];
// };
